package com.customization.webservice.AddSlabel.util;

import com.customization.commons.Console;
import com.customization.webservice.AddSlabel.beans.SLDataInfo;
import weaver.conn.RecordSet;
import weaver.file.FileSecurityUtil;
import weaver.general.BaseBean;
import weaver.hrm.company.SubCompanyComInfo;
import weaver.hrm.resource.ResourceComInfo;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.UUID;

public class SLDownload {

    public  InputStream adslAddSlabelFile(InputStream inputStream, int fileid, String extName) {
        long startTime = new Date().getTime();

        try {
            //判断是否启用了下载加密
            if ("0".equals(new BaseBean().getPropValue("weaver_AddSlabel", "is_mibiao"))) {

                RecordSet rs = new RecordSet();
                String secSql = "select docid  from imagefile,docimagefile  where imagefile.imagefileid =docimagefile.imagefileid and  docimagefile.imagefileid='" + fileid + "'";
                int docid = -1;
                rs.execute(secSql);
                if (rs.next()) {
                    docid = rs.getInt("docid");
                }

                if (docid > -1) {
                    String sql = "select classificationLevel,drafterName,issuerName,ClassifiedOrganizationName,classifiedTimeNum,classifiedTimeUnit,docid,requestid from cus_classified where docid='" + docid + "'";
                    rs.execute(sql);
                    if (rs.next()) {
                        String classificationLevel = rs.getString("classificationLevel");
                        if (!classificationLevel.equals("5")) {
                            ResourceComInfo rci = new ResourceComInfo();
                            SubCompanyComInfo sci = new SubCompanyComInfo();

                            int classifiedTimeNum = rs.getInt("classifiedTimeNum");
                            int classifiedTimeUnit = rs.getInt("classifiedTimeUnit");

                            Date date = new Date();//取时间
                            SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");//设置日期格式
                            String nowdate = df.format(date);
                            String ClassifiedTime = nowdate + "000000Z";
                            Calendar calendar = new GregorianCalendar();
                            calendar.setTime(date);

                            if (classifiedTimeUnit == 0) {//天
                                calendar.add(calendar.DATE, classifiedTimeNum);//把日期往后增加一天.整数往后推,负数往前移动
                            } else if (classifiedTimeUnit == 1) {//月
                                calendar.add(calendar.MONTH, classifiedTimeNum);//把日期往后增加一个月.整数往后推,负数往前移动
                            } else if (classifiedTimeUnit == 2) {//年
                                calendar.add(calendar.YEAR, classifiedTimeNum);//把日期往后增加一年.整数往后推,负数往前移动
                            } else if (classifiedTimeUnit == 3) {//长期
                                calendar.add(calendar.YEAR, 99);//把日期往后增加一年.整数往后推,负数往前移动
                            }

                            date = calendar.getTime();   //这个时间就是日期往后推一天的结果

                            String DeclassifiedTime = df.format(date) + "000000Z";

                            String uuid = docid+"-"+fileid+"-"+UUID.randomUUID().toString();
                            String destination = rs.getPropValue("weaver_AddSlabel", "sl_tempdir")
                                    + rs.getPropValue("weaver_AddSlabel", "splitstr") + uuid + "." + extName;
                            writeToLocal(destination, inputStream);//写到本地缓存中区

                            SLDataInfo dataInfo = new SLDataInfo();   //声明密级属性对象
                            dataInfo.setClassificationLevel(classificationLevel); //设置密级等级
                            dataInfo.setClassifiedTime(ClassifiedTime); //设置定密时间
                            dataInfo.setDeclassifiedTime(DeclassifiedTime); //设置解密具体时间
                            dataInfo.setDrafterName(rci.getLastname(rs.getString("drafterName"))); //设置文件起草人姓名
                            dataInfo.setDrafterID(rs.getString("drafterName")); //设置文件起草人账号ID
                            dataInfo.setIssuerName(rci.getLastname(rs.getString("issuerName"))); //设置文件签发人姓名
                            dataInfo.setIssuerID(rs.getString("issuerName")); //设置文件签发人账号ID
                            dataInfo.setClassifiedOrganizationName(sci.getSubcompanyname(rs.getString("ClassifiedOrganizationName"))); //设置定密单位名称
                            dataInfo.setClassifiedOrganizationID(rs.getString("ClassifiedOrganizationName")); //设置定密单位编号
                            dataInfo.setClassificationBasisDegree("3"); //设置定密依据密级等级



                            String jiaMiuuid = "密" + uuid;
                            String jiaMiDestination = rs.getPropValue("weaver_AddSlabel", "sl_tempdir")
                                    + rs.getPropValue("weaver_AddSlabel", "splitstr") + jiaMiuuid + "." + extName;
                            ServiceUtil.adslAddSlabel(destination, dataInfo.getXmlPath(), jiaMiDestination);

                            File targetfile = new File(jiaMiDestination);
                            Console.log("targetfile:size()" + targetfile.length());

                            inputStream = file2InputStream(targetfile);

                            if (rs.getPropValue("weaver_AddSlabel", "sl_savetemp").equals("0")) {
                                FileSecurityUtil.deleteFile(targetfile);
                            }
                            //删除加密前的缓存文件
                            targetfile = new File(destination);
                            FileSecurityUtil.deleteFile(targetfile);
                        } else {
                            Console.log(fileid + "公文等级为5,不加密");

                        }
                    }else{
                        Console.log(fileid + "不是公文，不加密");
                    }
                }
            }else{
                Console.log(fileid + "未启用加密功能");
            }
        } catch (Exception e) {
            e.printStackTrace();
            String content = e.toString();
            Console.log(e.toString());
            inputStream = new ByteArrayInputStream(content.getBytes());
        }finally {




        }

        long endTime = new Date().getTime();
        Console.log("filed:" + fileid + "加密耗时：" + (endTime - startTime) + "ms");
        return inputStream;

    }

    /**
     * 将InputStream写入本地文件
     *
     * @param destination 写入本地目录
     * @param input       输入流
     * @throws IOException IOException
     */
    public static void writeToLocal(String destination, InputStream input) {
        try {
            int index;
            byte[] bytes = new byte[1024];
            FileOutputStream downloadFile = null;

            downloadFile = new FileOutputStream(destination);

            while ((index = input.read(bytes)) != -1) {
                downloadFile.write(bytes, 0, index);
                downloadFile.flush();
            }
            input.close();
            downloadFile.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 将file转换为inputStream
     *
     * @param file
     * @return
     * @throws FileNotFoundException
     */
    public static InputStream file2InputStream(File file) {
        try {
            return new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}
